layui.use(['table', 'admin', 'ax', 'laydate', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var laydate = layui.laydate;

    /* 地图方法 */
    var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 6,
        center: [117.222439,36.669593]
    });

    // 车辆数据模型
    var vehicles = [];

    // 创建车辆标记和信息窗体
    function createVehicleMarker(vehicle) {
        var markerContent = `
                    <div class="custom-content-marker">
                        <div class="markerInfo">
                            <strong> 实时位置 </strong><br/>
                            货运订单号: <span style="color: red;">${vehicle.info}</span><br/>
                            车牌: <span style="color: red;">${vehicle.id}</span><br/>
                            时间:<span style="color: #070202;">${vehicle.time}</span><br/>
                        </div>
                    </div>`;

        // "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png"
        var icon = new AMap.Icon({
            size: new AMap.Size(43, 53),
            image: "https://s21.ax1x.com/2024/10/10/pAJYYFJ.png",
            imageSize: new AMap.Size(43, 53)
        });

        var marker = new AMap.Marker({
            position: vehicle.position,
            map: map,
            title: vehicle.id,
            icon: icon,
            offset: new AMap.Pixel(-22, -26),
            autoRotation: true,
        });


        // 创建信息窗体
        vehicle.infoWindow = new AMap.InfoWindow({
            content: markerContent,
            offset: new AMap.Pixel(0, -28)
        });

        // 点击标记时打开信息窗体
        marker.on('click', function() {
            if (markerContent){
                vehicle.infoWindow.open(map, marker.getPosition());
            }
        });

        return marker;
    }


    function clearOldData() {
        map.clearMap();
    }
    // // 初始化所有车辆
    // vehicles.forEach(function (vehicle) {
    //     vehicle.marker = createVehicleMarker(vehicle);
    // });

    // 更新车辆位置
    function updateVehiclePosition(vehicle, newPosition) {
        vehicle.position = newPosition;
        vehicle.marker.setPosition(newPosition);
    }

    // 请求车辆位置更新
    function requestVehiclePositions() {
        var operateId = $("#searchSelect").val();
        var queryData = {};
        queryData['operateId'] = operateId;

        // 检查是否选择了项目
        if (!operateId) {
            layer.msg('请先选择项目', {icon: 0}, function(){});
            return;
        }
        // clearOldData();
        map.clearMap();
        console.log(11111111111)
        $.getJSON(Feng.ctxPath + '/MapTransport/queryTerminalLocationWebNew',queryData, function (response) {
            console.log("res:",response)
            vehicles = [];
            response.forEach(function (item) {
                var vehicleData = item.data;
                var terminalName = item.terminalName;
                var location = vehicleData.location.split(',').map(Number);
                var parts = item.traceName.split('-');
                var traceName = parts.slice(1).join('-');
                var pointTime = new Date(vehicleData.locatetime).toLocaleString();

                // 查找对应的车辆
                var vehicle = vehicles.find(v => v.id === terminalName);

                // 如果找不到，则创建新的车辆对象
                if (!vehicle) {
                    vehicle = {
                        id: terminalName,
                        position: location,
                        status: 'active',
                        info: traceName,
                        marker: null,
                        infoWindow: null,
                        time: pointTime
                    };
                    // console.log("vehicle：",vehicle)
                    vehicle.marker = createVehicleMarker(vehicle);
                    vehicles.push(vehicle);
                } else {
                    // 更新已有车辆的位置
                    updateVehiclePosition(vehicle, location);
                }
            });
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.error('Error fetching data:', textStatus, errorThrown);
        });
    }

    // 定时器变量
    var vehiclePositionInterval;

    $('#searchButton').on('click', function() {
        // 清除已有的定时器
        if (vehiclePositionInterval) {
            clearInterval(vehiclePositionInterval);
        }

        // 请求车辆位置
        requestVehiclePositions();

        // 设置定时器，每60秒调用一次requestVehiclePositions
        vehiclePositionInterval = setInterval(requestVehiclePositions, 60000);
    });


    // 设置地图视图
    map.setFitView(null, false, [150, 60, 100, 60]);
});